<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js对象之代理实现双向数据绑定</title>
</head>
<body>
  <ul>
    <li>可通过Proxy实现类似Vue的双向数据绑定功能</li>
  </ul>
  <input type="text" v-model="content"/>
  <h2 v-bind="content"></h2>
  <input type="text" v-model="title"/>
  <input type="text" v-model="title"/>
  <h2 v-bind="title"></h2>
  <script>
    // 双向数据绑定
    function View() {
      const proxy = new Proxy({}, {
        get(obj, prop) {},
        set(obj, prop, val) {
          document.querySelectorAll(`[v-model=${prop}]`).forEach(item => item.value = val)
          document.querySelectorAll(`[v-bind=${prop}]`).forEach(item => item.innerHTML = val)
        }
      })
      this.init = function () {
        const elems = document.querySelectorAll('[v-model]')
        elems.forEach(item => {
          item.addEventListener('keyup', function () {
            proxy[item.getAttribute('v-model')] = item.value
          })
        })
      }
    }
    new View().init()
  </script>
</body>
</html>
